package com.mycompany.lctwitter.action.user;

import java.util.Date;

import javax.annotation.Resource;

import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.hibernate.Hibernate;

import com.mycompany.lctwitter.action.AbstractAction;
import com.mycompany.lctwitter.biz.model.UserModel;
import com.mycompany.lctwitter.persist.model.Location;
import com.mycompany.lctwitter.persist.model.User;
import com.mycompany.lctwitter.persist.service.FootprintService;
import com.mycompany.lctwitter.persist.service.LocationService;
import com.mycompany.lctwitter.persist.service.UserService;
import com.opensymphony.xwork2.Action;

@Results( { @Result(name = Action.SUCCESS, type = "redirect", location = "/message/list"),
		@Result(name = Action.INPUT, type = "redirect", location = "/user/login-page") })
public class LoginAction extends AbstractAction {

	private static final long serialVersionUID = -8991409214548470501L;
	private String userName;
	private String password;
	private long locationId;

	@Resource
	private UserService userService;

	@Resource
	private FootprintService footprintService;

	@Resource
	private LocationService locationService;

	public void setUserName(String userName) {
		this.userName = userName;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public void setLocationId(long locationId) {
		this.locationId = locationId;
	}

	@Override
	public String execute() {
		User user = userService.login(userName, password);
		if (user == null)
			return INPUT;

		Location location = locationService.find(locationId);
		footprintService.add(user, location, new Date());

		Hibernate.initialize(location);// locationService.find()方法底层调用了Session的load()方法，它会采用动态代理的方式延迟加载location实体，这里需要立即加载。
		UserModel logindUser = new UserModel(user, location);
		session.put(LOGINED_USER, logindUser);

		return SUCCESS;
	}
}
